<template>
  <div class="tree_container">
    <div class="tree_wrap">
      <button @click="setCheckedKeys">设置目前勾选的节点</button>
      <el-tree ref="tree" :data="data" show-checkbox node-key="id" :props="defaultProps" @node-click="nodeClick" @check="checkClick" @current-change="changeClick" highlight-current lazy :load="load"></el-tree>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: [
        { id: 1, label: '1', children: [{ id: 1.1, label: '1.1' }, { id: 1.2, label: '1.2' }] },
        { id: 2, label: '2', children: [{ id: 2.1, label: '2.1' }, { id: 2.2, label: '2.2', children: [{ id: 2.21, label: '2.21' }] }] }
      ],
      defaultProps: {
        children: 'children',
        label: 'label',
        isLeaf: (data, node) => { console.log('判断是否为子叶节点', data, node); if (node.level == 2) { return true; } else { return false } }
      }
    };
  },
  methods: {
    setCheckedKeys() {console.log(1,1);this.$refs.tree.setCheckedKeys([1])},
    nodeClick(a, b, c) {
      console.log('点击节点nodeClick', a, b, c)
    },
    checkClick(a, b, c) {
      console.log('触发check', a, b, c)
      console.log('返回目前被选中的节点所组成的数组',this.$refs.tree.getCheckedNodes())
      console.log('半选中的节点的 key 所组成的数组',this.$refs.tree.getHalfCheckedKeys())
    },
    changeClick(a, b, c) {
      console.log('触发changeClick', a, b, c)
    },
    load(node, resolve) {
      console.log('懒加载node', node)
      if (node.level === 1) {
        return resolve([{ id: 1.1, label: '1.1' }, { id: 1.2, label: '1.2' }]);
      } else {
        return resolve([
          { id: 1, label: '1', children: [{ id: 1.1, label: '1.1' }, { id: 1.2, label: '1.2' }] },
          { id: 2, label: '2', children: [{ id: 2.1, label: '2.1' }, { id: 2.2, label: '2.2', children: [{ id: 2.21, label: '2.21' }] }] }
        ])
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.tree_wrap {
  width: 300px;
  border: 1px solid;
  margin: auto;
  margin-top: 20px;
}
</style>